<template>
  <el-container>
    <el-header>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.prevent>
        <el-form-item label="应用名">
          <el-input v-model="searchForm.name" placeholder="应用名" @keyup.enter="onSearch"></el-input>
        </el-form-item>
        <el-form-item label="应用类型">
          <el-select v-model="searchForm.type" placeholder="应用类型" >
            <el-option
              v-for="item in appTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="default" @click="onReset">重置</el-button>
          <el-button type="default" @click="onAddApp" icon="CirclePlus"
            >新增应用</el-button
          >
        </el-form-item>
        >
      </el-form>
    </el-header>
    <el-divider direction="horizontal"></el-divider>
    <el-main class="cus-main">
      <el-table :data="appList" style="width: 100%">
        <el-table-column
          prop="id"
          label="ID"
          v-if="false"
        ></el-table-column>
        <el-table-column
          prop="code"
          label="应用编码"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="应用名"
        ></el-table-column>
        <el-table-column prop="type" label="应用类型">
          <template #default="scope">
              {{
                appTypes.find((c) => c.value === scope.row.type).label
              }}
          </template>   
        </el-table-column>
        <el-table-column
          prop="description"
          label="应用描述"
        ></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button link type="primary" @click="onEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '修改应用' : '新增应用'"
      width="30%"
      header-class="dialog-custom-header"
    >
    <el-divider direction="horizontal" style="width: 95%"></el-divider>
      <el-form :model="newAppForm" label-width="70px">
        <el-form-item label="应用编码">
          <el-input v-model="newAppForm.code" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="应用名">
          <el-input v-model="newAppForm.name"></el-input>
        </el-form-item>
        <el-form-item label="应用类型">
          <el-select v-model="newAppForm.type" placeholder="应用类型">
            <el-option
              v-for="item in appTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用描述">
          <el-input v-model="newAppForm.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { get, post, put, del } from "@/utils/request";
const appTypes = ref([]);
const dialogVisible = ref(false);
const isEdit = ref(false); // 是否为修改模式
const currentEditId = ref(null); // 当前编辑的应用ID
const searchForm = reactive({
  name: null,
  type: null,
});
const newAppForm = reactive({
  code: null,
  name: null,
  type: null,
  description: null,
});
const appList = ref([]);


const onSearch = () => {
  // 实现查询逻辑
  let params = {
    name: searchForm.name,
    type: searchForm.type,
  };
  get("/apm/apps", params)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        appList.value = res.data.data.data;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onAddApp = () => {
  isEdit.value = false;
  Object.keys(newAppForm).forEach((key) => {
    newAppForm[key] = null;
  });
  dialogVisible.value = true;
};

const onReset = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = null;
  });
};

const onEdit = (row) => {
  isEdit.value = true;
  currentEditId.value = row.id;
  Object.assign(newAppForm, row);
  dialogVisible.value = true;
};

const onDelete = (row) => {
  del("/apm/apps/" + row.id)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        appList.value = appList.value.filter((item) => item.id !== row.id);
        ElMessage.success("删除成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onSubmit = async () => {
  let succ = false;
  if (isEdit.value) {
    const index = appList.value.findIndex(
      (item) => item.id === currentEditId.value
    );
    if (index !== -1) {
      appList.value[index] = { ...newAppForm, id: currentEditId.value };
    }
    let payload = {
      name: newAppForm.name,
      type: newAppForm.type,
      description: newAppForm.description,
    };
    await put("/apm/apps/" + currentEditId.value, payload)
      .then((res) => {
        // console.log("搜索结果:", res);
        if (res.data.code === 0) {
          succ = true;
          ElMessage.success("更新成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  } else {
    // 后端写入
    let payload = {
      code: newAppForm.code,
      name: newAppForm.name,
      type: newAppForm.type,
      description: newAppForm.description,
    };
    await post("/apm/apps", payload)
      .then((res) => {
        if (res.data.code === 0) {
          appList.value.push({
            ...newAppForm,
            id: res.data.data.id,
          });
          succ = true;
          ElMessage.success("新增成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  }
  if (succ) {
    dialogVisible.value = false;
  }
  
};

onMounted(async () => {
  // 初始化字典
  await get("/apm/apps/types")
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        appTypes.value = res.data.data.data;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
  onSearch();
});
</script>


